let mongo = require("mongodb").MongoClient;
let assert = require("assert");

let url = "mongodb://localhost:2333/test";
mongo.connect(url, function(err, db){
    assert.equal(null, err);
    console.log("MongoDB connect success.");
    
    // insert document
    // insertDocument(db, function(){
    //     db.close();
    // });

    // find
    // findDocuments(db, function(docs){
    //     db.close();
    // });

    // update
    updateDocument(db, function(){
        findDocuments(db, function(){
            db.close();
        });
    })

});

function insertDocument(db, callback){
    let col = db.collection("user");
    
    col.insertMany([
        { name : "name01", age : 20 },
        { name : "name02", age : 21 },
        { name : "name03", age : 22 },
    ], function(err, res){
        assert.equal(err, null);
        assert.equal(3, res.result.n);
        assert.equal(3, res.ops.length);

        console.log("insert 3 documents into the collection");
        callback(res);
    });
}

function findDocuments(db, callback){
    let col = db.collection("user");

    col.find({}).toArray(function(err, docs){
        assert.equal(err, null);
        console.log("find all documnets from collection");

        console.log(docs);
        callback(docs);
    });
}

function updateDocument(db, callback){
    let col = db.collection("user");
    col.updateOne({ name : "name01" }, {
        $set : {
            age : 233
        }
    }, function(err, res){
        assert.equal(err, null);
        console.log(1, res.result.n);

        console.log("Update document form collection success.");
        callback(res);
    });
}